<?php
    $DEBUG = false;
    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    if (!isLoggedIn()) {
        exit();
    }
    $DO_GET = $DEBUG;
    $IN = $DO_GET ? $_GET : $_POST;
    include_once "db/db_cse305.php";
    header ("Expires: Sat, 1 Jan 2000 01:00:00 GMT");
    header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header ("Cache-Control: no-cache, must-revalidate");
    header ("Pragma: no-cache");
    if (!isset($IN["stocks"])) {
        if ($DEBUG)
            echo "'stocks' not set.<br />";
        exit();
    }
    
    $q = $IN["stocks"];
    if ($q == "") exit();
    if (!is_array($q)) {
        $q = split(",", $q);
    }
    
    //Cobble together search terms
    $query = "SELECT * FROM stocks WHERE ";
    $where = sprintf("StockSymbol = '%s'", mysql_real_escape_string(trim($q[0])));
    $i = 1;
    while ($i < count($q)) {
        $where .= sprintf(" || StockSymbol = '%s'", mysql_real_escape_string(trim($q[$i])));
        $i++;
    }
    $query = $query . $where . " ORDER BY StockSymbol DESC";
    $result = mysql_query($query) or die(mysql_error());
    $arr = array();
    while ($row = mysql_fetch_array($result)) {
        $stock = array();
        $stock["StockName"] = $row["StockName"];
        $stock["Shares"] = $row["NumberOfShares"];
        $stock["SharePrice"] = $row["SharePrice"];
        $arr[$row["StockSymbol"]] = $stock;
    }
    mysql_free_result($result);
    header("Content-Type: application/json");
    echo json_encode($arr);
?>
